package com.ehome.poct.base.device.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ehome.core.service.AbstractCrudServiceImpl;
import com.ehome.exception.BizException;
import com.ehome.poct.base.api.constant.DeviceType;
import com.ehome.poct.base.api.constant.PackageType;
import com.ehome.poct.base.api.dto.device.*;
import com.ehome.poct.base.api.virtual.TestDeviceService;
import com.ehome.poct.base.api.vo.device.TestDeviceClinicVO;
import com.ehome.poct.base.api.vo.device.TestDevicePrinterVO;
import com.ehome.poct.base.api.vo.device.TestDeviceVO;
import com.ehome.poct.base.device.repository.TestDevicePrinterRepository;
import com.ehome.poct.base.device.repository.TestDeviceRepository;
import com.ehome.poct.base.device.repository.TestDeviceVersionRelationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 设备表SerivceImlp
 *
 * @author muqiu
 * @Date 2022-02-24 09:23
 */
@Service
public class TestDeviceServiceImpl extends AbstractCrudServiceImpl<TestDeviceDTO> implements TestDeviceService {

    @Autowired private TestDeviceRepository testDeviceRepository;
    
    @Autowired
    private TestDeviceVersionRelationRepository testDeviceVersionRelationRepository;

    @Autowired
    private TestDevicePrinterRepository testDevicePrinterRepository;

    @Override
    public TestDeviceVO getBySno(String sno) {
        return testDeviceRepository.getBySno(sno);
    }
    
    @Override
    public List<TestDeviceClinicVO> getDeviceBySno(TestDeviceClinicDTO testDeviceClinicDTO) {
        return testDeviceRepository.getDeviceBySno(testDeviceClinicDTO);
    }
    
    /**
     * 校验是否存在这个设备编号
     * @param sno 设备号
     * @return true(已存在)/false(不存在)
     */
    @Override
    public Boolean isExistence(String sno) {
        return testDeviceRepository.isExistence(sno);
    }

    /**
     * 新增设备
     * @param sno 设备编号
     * @return true(添加成功)/false(添加失败)
     */
    @Override
    public Boolean addDevice(String sno,Integer deviceType) {
        boolean exist = this.isExistence(sno);
        if(!exist){
            return testDeviceRepository.addDevice(sno,deviceType);
        }
        return false;
    }

    @Override
    public void editStatus(DeviceStatusDTO dto) {
    testDeviceRepository.updateStatus(dto);
    }

    @Override
    public Boolean isBind(String sno, Long clinicId) {
        return testDeviceRepository.isBind(sno,clinicId);
    }
    
    @Override
    public List<TestDeviceVO> getByClinic(Long clinicId) {
        return testDeviceRepository.getByClinic(clinicId);
    }
    
    @Override
    public TestDeviceVO getByClinic(Long clinicId, String sno, Integer deviceType) {
        return testDeviceRepository.getByClinic(clinicId, sno, deviceType);
    }

    @Override
    public void versionReport(VersionReportDTO dto) {
        if (dto == null || StrUtil.isEmpty(dto.getSno())) {
            throw new BizException(202,"版本上报失败，原因： 上报信息为空或者设备编号为空!");
        }
        TestDeviceDTO tdd = new TestDeviceDTO();
        tdd.setSno(dto.getSno());
        List<TestDeviceDTO> list = testDeviceRepository.list(tdd);
        TestDeviceDTO first = CollUtil.getFirst(list);
        if (first != null) {
            PackageType packageType = PackageType.getPackageTypeEnum(dto.getPackageType());
            Integer deviceType = DeviceType.getDeviceType(dto.getProjectName());
            TestDeviceVersionRelationDTO tdvrd = new TestDeviceVersionRelationDTO();
            tdvrd.setDeviceType(deviceType);
            tdvrd.setDeviceId(first.getTestDeviceId());
            tdvrd.setSno(first.getSno());
            tdvrd.setPackageType(dto.getPackageType());
            if (packageType.compareTo(PackageType.SOFTWARE) == 0) {
                tdvrd.setPackageId(dto.getPackageId());
                tdvrd.setPackageName(dto.getPackageName());
            }
            TestDeviceVersionRelationDTO relationDTO = CollUtil.getFirst(testDeviceVersionRelationRepository.list(tdvrd));
            tdvrd.setVersionCode(dto.getVersionCode());
            tdvrd.setVersion(dto.getVersion());
            if(relationDTO != null){
                if (!relationDTO.getVersion().equals(dto.getVersion())) {
                    testDeviceVersionRelationRepository.update(relationDTO.getDeviceVersionRelationId().toString(),tdvrd);
                }
            }else{
                testDeviceVersionRelationRepository.save(tdvrd);
            }
        }
    }

    @Override
    public TestDeviceVO getByClinic(Long clinicId,  Integer deviceType) {
        return testDeviceRepository.getByClinicAndType(clinicId, deviceType);
    }

    @Override
    public List<Long> getAllBindClinic() {
        return testDeviceRepository.getAllBindClinic();
    }

    @Override
    public void devicePrinter(TestDevicePrinterDTO testDevicePrinterDTO) {
        //根据sno号查询是否已经有记录
        var printer = testDevicePrinterRepository.selectOne(new TestDevicePrinterDTO().setSno(testDevicePrinterDTO.getSno()));
        if(ObjectUtil.isEmpty(printer)){
            testDevicePrinterRepository.insert(testDevicePrinterDTO);
        }else {
            testDevicePrinterRepository.update(printer.getTestDevicePrinterId(), testDevicePrinterDTO);
        }
    }

    @Override
    public List<TestDevicePrinterVO> getDevicePrinter(String sno) {
        //根据sno号获取诊所下所有设备
        final var device = testDeviceRepository.getBySno(sno);
        //查询设备连接打印机信息
        return testDevicePrinterRepository.listBySno(device.getTermClinicId());
    }

    @Override
    public void insetOrUpdate(TestDeviceDTO dto) {
        final var device = this.selectOne(new TestDeviceDTO().setSno(dto.getSno()));
        Optional.ofNullable(device).ifPresentOrElse(
                it -> this.updateSelective(it.getTestDeviceId(),
                        new TestDeviceDTO().setExpirationDate(dto.getExpirationDate()).setTimeUnit(dto.getTimeUnit()).setValidDate(dto.getValidDate())),
                () -> this.insert(dto));
    }
}